import time
import requests
import re

# 企业微信的API信息
corpid = "your_corp_id"  # 替换为实际的企业微信CorpID
agent_id = "your_agent_id"  # 替换为实际的企业微信AgentID
access_token = "your_access_token"  # 替换为实际的企业微信Access Token

# 日志文件路径
# log_file = "/home/admin/app/internal_server/websocket_server.log"  # 替换为实际的日志文件路径
log_file = "./websocket_server.log"  # 替换为实际的日志文件路径


def send_to_wechat(message):
    # 准备发送到企业微信的数据
    message_data = {"msgtype": "text",
                    "text": {
                        "content": f"{message}<@yaodong>"
                    }
                    }

    # 使用企业微信的消息推送API发送消息
    send_message_url = f"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=f986ca7d-33f1-4f24-8a9a-227147636157"
    response = requests.post(send_message_url, json=message_data)

    if response.status_code == 200:
        print("Message sent successfully")
    else:
        print("Failed to send message:", response.text)


def monitor_log_file():
    with open(log_file, "r") as f:
        for line in f:
            # 匹配包含特定信息的日志行
            if "服务异常" in line and "session_id:" in line:
                # 在此处添加您的逻辑，处理匹配到的日志行
                
                # 例如，您可以将日志信息发送到企业微信
                send_to_wechat(line.strip())


if __name__ == "__main__":
    while True:
        try:
            # 每隔一段时间（例如10秒）监控日志文件
            monitor_log_file()
            time.sleep(10)
        except KeyboardInterrupt:
            # 如果用户中断程序（例如按下Ctrl+C），则退出循环
            break
